package cn.antcore.common.security.mobile;

import cn.antcore.common.security.handler.GoAuthenticationLoginFailureHandler;
import cn.antcore.common.security.handler.GoAuthenticationLoginSuccessHandler;
import cn.antcore.service.AuthService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;

/**
 * 短信验证码模式 配置
 * <br>
 * Created by Hong 2024/5/28
 **/
@Component
public class MobileLoginConfigurer implements SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> {

    private final ObjectMapper objectMapper;
    private final AuthService authService;

    public MobileLoginConfigurer(ObjectMapper objectMapper, AuthService authService) {
        this.objectMapper = objectMapper;
        this.authService = authService;
    }

    @Override
    public void init(HttpSecurity builder) throws Exception {

    }

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        // 短信验证码登录
        MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
        mobileAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        mobileAuthenticationFilter.setSessionAuthenticationStrategy(builder.getSharedObject(SessionAuthenticationStrategy.class));
        mobileAuthenticationFilter.setSecurityContextRepository(builder.getSharedObject(SecurityContextRepository.class));
        mobileAuthenticationFilter.setAuthenticationSuccessHandler(new GoAuthenticationLoginSuccessHandler(objectMapper));
        mobileAuthenticationFilter.setAuthenticationFailureHandler(new GoAuthenticationLoginFailureHandler(objectMapper));
        MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider(authService);
        builder.authenticationProvider(mobileAuthenticationProvider)
                .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
